package com.shudes.eval;

import java.util.*;

import com.shudes.game.*;

public class EquityObservationCalculator {

	protected EquityInput equityInput;
	
	public EquityObservationCalculator(EquityInput input) {
		this.equityInput=input; 
	}
	
	@SuppressWarnings("unchecked")
	public EquityObservation calculate(Board b) { 
		EquityObservation observ;
		HandStrength strength;
		TreeSet<HandStrength> set; 		
		HandStrength last;
		Set<HoleCards> winners; 
		
		ArrayList<Card> c; 
		c = new ArrayList<Card>(b.getCards()); 
		Collections.sort(c); 
		Collections.reverse(c); 
		
		System.out.print("..calculating for board: " + c);   

		set = new TreeSet<HandStrength>(); 
		observ = new EquityObservation(equityInput, b); 
		for(HoleCards hc : observ.getResultMap().keySet()) {
			strength = calcHandStrength(hc,b);
			set.add(strength); 
			observ.getHandStrengthMap().put(hc, strength); 
		}
		
		last = set.last();
		winners = new HashSet<HoleCards>();
		
		for(Iterator it=set.iterator(); it.hasNext();) {
			HandStrength hs = (HandStrength) it.next(); 
			if(hs.compareTo(last) >= 0) { 
				winners.add(hs.getHand().getHoleCards()); 
			}
		}

		System.out.println(".. winner(s) -> " + winners); 
		
		if(winners.size()>1) { 
			observ.setTie(winners); 
		} else { 
			observ.setWinner(winners.iterator().next()); 
		}
		
        return observ;
	}
	
	protected HandStrength calcHandStrength(HoleCards hc, Board b ) { 
		return new HandEvaluator(new Hand(hc, b)).getHandStrength(); 
	}	
	
}
